/*helper Methods*/
function ShowLocalDate() {
    var dNow = new Date();
    var localdate = (dNow.getMonth() + 1) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();
    return localdate;
}
function AddRow(table, button) {
    if (button.data('row')) {
        button.data('row', 'false');
        var lastrow = $(table).find('tr:last');
        lastrow.after(lastrow[0].outerHTML);
    }
    else {
        button.data('row', 'true');
        button.parents('tr').remove();
    }
}
/* JS */


/* Navigation */

$(document).ready(function () {

    $(window).resize(function () {
        if ($(window).width() >= 765) {
            $(".sidebar #nav").slideDown(350);
        }
        else {
            $(".sidebar #nav").slideUp(350);
        }
    });


    $("#nav > li > a").on('click', function (e) {
        if ($(this).parent().hasClass("has_sub")) {
            e.preventDefault();
        }

        if (!$(this).hasClass("subdrop")) {
            // hide any open menus and remove all other classes
            $("#nav li ul").slideUp(350);
            $("#nav li a").removeClass("subdrop");

            // open our new menu and add the open class
            $(this).next("ul").slideDown(350);
            $(this).addClass("subdrop");
        }

        else if ($(this).hasClass("subdrop")) {
            $(this).removeClass("subdrop");
            $(this).next("ul").slideUp(350);
        }

    });
});

$(document).ready(function () {
    $(".sidebar-dropdown a").on('click', function (e) {
        e.preventDefault();

        if (!$(this).hasClass("open")) {
            // hide any open menus and remove all other classes
            $(".sidebar #nav").slideUp(350);
            $(".sidebar-dropdown a").removeClass("open");

            // open our new menu and add the open class
            $(".sidebar #nav").slideDown(350);
            $(this).addClass("open");
        }

        else if ($(this).hasClass("open")) {
            $(this).removeClass("open");
            $(".sidebar #nav").slideUp(350);
        }
    });

});

/* Widget close */

$('.wclose').click(function (e) {
    e.preventDefault();
    var $wbox = $(this).parent().parent().parent();
    $wbox.hide(100);
});

/* Widget minimize */

$('.wminimize').click(function (e) {
    e.preventDefault();
    var $wcontent = $(this).parent().parent().next('.widget-content');
    if ($wcontent.is(':visible')) {
        $(this).children('i').removeClass('icon-chevron-up');
        $(this).children('i').addClass('icon-chevron-down');
    }
    else {
        $(this).children('i').removeClass('icon-chevron-down');
        $(this).children('i').addClass('icon-chevron-up');
    }
    $wcontent.toggle(500);
});

/* Calendar */

$(document).ready(function () {

    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();

    $('#calendar').fullCalendar({
        header: {
            left: 'prev',
            center: 'title',
            right: 'month,agendaWeek,agendaDay,next'
        },
        editable: true,
        events: [
          {
              title: 'All Day Event',
              start: new Date(y, m, 1)
          },
          {
              title: 'Long Event',
              start: new Date(y, m, d - 5),
              end: new Date(y, m, d - 2)
          },
          {
              id: 999,
              title: 'Repeating Event',
              start: new Date(y, m, d - 3, 16, 0),
              allDay: false
          },
          {
              id: 999,
              title: 'Repeating Event',
              start: new Date(y, m, d + 4, 16, 0),
              allDay: false
          },
          {
              title: 'Meeting',
              start: new Date(y, m, d, 10, 30),
              allDay: false
          },
          {
              title: 'Lunch',
              start: new Date(y, m, d, 12, 0),
              end: new Date(y, m, d, 14, 0),
              allDay: false
          },
          {
              title: 'Birthday Party',
              start: new Date(y, m, d + 1, 19, 0),
              end: new Date(y, m, d + 1, 22, 30),
              allDay: false
          },
          {
              title: 'Click for Google',
              start: new Date(y, m, 28),
              end: new Date(y, m, 29),
              url: 'http://google.com/'
          }
        ]
    });

});

/* Progressbar animation */

setTimeout(function () {

    $('.progress-animated .progress-bar').each(function () {
        var me = $(this);
        var perc = me.attr("data-percentage");

        //TODO: left and right text handling

        var current_perc = 0;

        var progress = setInterval(function () {
            if (current_perc >= perc) {
                clearInterval(progress);
            } else {
                current_perc += 1;
                me.css('width', (current_perc) + '%');
            }

            me.text((current_perc) + '%');

        }, 600);

    });

}, 600);

/* Slider */

$(function () {
    // Horizontal slider
    $("#master1, #master2").slider({
        value: 60,
        orientation: "horizontal",
        range: "min",
        animate: true
    });

    $("#master4, #master3").slider({
        value: 80,
        orientation: "horizontal",
        range: "min",
        animate: true
    });

    $("#master5, #master6").slider({
        range: true,
        min: 0,
        max: 400,
        values: [75, 200],
        slide: function (event, ui) {
            $("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
        }
    });


    // Vertical slider 
    $("#eq > span").each(function () {
        // read initial values from markup and remove that
        var value = parseInt($(this).text(), 10);
        $(this).empty().slider({
            value: value,
            range: "min",
            animate: true,
            orientation: "vertical"
        });
    });
});



/* Support */

$(document).ready(function () {
    $("#slist a").click(function (e) {
        e.preventDefault();
        $(this).next('p').toggle(200);
    });
});

/* Scroll to Top */


$(".totop").hide();

$(function () {
    $(window).scroll(function () {
        if ($(this).scrollTop() > 300) {
            $('.totop').slideDown();
        }
        else {
            $('.totop').slideUp();
        }
    });

    $('.totop a').click(function (e) {
        e.preventDefault();
        $('body,html').animate({ scrollTop: 0 }, 500);
    });

});

/* jQuery Notification */

$(document).ready(function () {

    setTimeout(function () { noty({ text: '<strong>Howdy! Hope you are doing good...</strong>', layout: 'topRight', type: 'information', timeout: 15000 }); }, 7000);

    setTimeout(function () { noty({ text: 'This is an all in one theme which includes Front End, Admin & E-Commerce. Dont miss it. Grab it now', layout: 'topRight', type: 'alert', timeout: 13000 }); }, 9000);

});


$(document).ready(function () {

    $('.noty-alert').click(function (e) {
        e.preventDefault();
        noty({ text: 'Some notifications goes here...', layout: 'topRight', type: 'alert', timeout: 2000 });
    });

    $('.noty-success').click(function (e) {
        e.preventDefault();
        noty({ text: 'Some notifications goes here...', layout: 'top', type: 'success', timeout: 2000 });
    });

    $('.noty-error').click(function (e) {
        e.preventDefault();
        noty({ text: 'Some notifications goes here...', layout: 'topRight', type: 'error', timeout: 2000 });
    });

    $('.noty-warning').click(function (e) {
        e.preventDefault();
        noty({ text: 'Some notifications goes here...', layout: 'bottom', type: 'warning', timeout: 2000 });
    });

    $('.noty-information').click(function (e) {
        e.preventDefault();
        noty({ text: 'Some notifications goes here...', layout: 'topRight', type: 'information', timeout: 2000 });
    });

});


/* Date picker */

$(function () {
    $('#datetimepicker1').datetimepicker({
        pickTime: false
    });
});

$(function () {
    $('#datetimepicker2').datetimepicker({
        pickDate: false
    });
});




/* CL Editor */

$(".cleditor").cleditor({
    width: "auto",
    height: "auto"
});

/* Modal fix */

$('.modal').appendTo($('body'));

/* Pretty Photo for Gallery*/

jQuery("a[class^='prettyPhoto']").prettyPhoto({
    overlay_gallery: false, social_tools: false
});

$(document).ready(function () {
    $('body').on({
        click: function () {
            var self = $(this);
            AddRow(self.parents('table'), self);
            self.find('i').toggleClass('icon-plus icon-minus');
        }
    }, '[data-row]');
    $('body').on({
        click: function () {
            var self = $(this);
            var action = self.parents('[data-action="Mode"]');
            action.after(action[0].outerHTML);
        }
    }, '[data-action="AddMode"]');
});

/* Bootstrap plugin wizard */
$(document).ready(function () {
    $('#rootwizard').bootstrapWizard({
        onTabShow: function (tab, navigation, index) {
            var $total = navigation.find('li').length;
            var $current = index + 1;
            var $percent = ($current / $total) * 100;
            $('#rootwizard').find('.bar').css({ width: $percent + '%' });
        },
        onNext: function (tab, navigation, index) {
            switch ($(tab.find('a').attr('href')).data('name')) {
                case "pluigninfo":
                    plugin.PluginName = $(tab.find('a').attr('href')).find('#PluginName').val();
                    plugin.CreatedDate = ShowLocalDate();
                    plugin.ModifiedDate = ShowLocalDate();
                    break;
                case "actioninfo":
                    var currentURL = document.location;
                    var modes = new Array();
                    $(tab.find('a').attr('href')).find('.widget[data-action="Mode"]:visible').each(function () {
                        var element = $(this);
                        var Mode = new Object();
                        Mode.ModeName = element.find('[data-action="ModeName"]').val();
                        Mode._id = "";
                        Mode.IsActive = false;
                        var ModeProperties = new Array();
                        element.find('[data-action="ModeProperties"] tr:has(td)').each(function () {
                            var Property = new Object();
                            Property.PropertyName = $(this).find('td:nth-child(2) input').val();
                            Property.Key = $(this).find('td:nth-child(3) input').val();
                            Property.Value = $(this).find('td:nth-child(4) input').val();
                            ModeProperties.push(Property);
                        });
                        Mode.ModeProperties = ModeProperties;
                        modes.push(Mode);
                    });
                    plugin.Modes = modes;
                    //call ajax method to generate
                    $.ajax({
                        type: 'POST',
                        url: currentURL.href,
                        cache: false,
                        data: JSON.stringify({ plugin: plugin }),
                        dataType: 'json',
                        contentType: 'application/json; charset=utf-8',
                        success: function (data, textStatus, xhr) {
                            plugin = data.plugin;
                            $('body').append('<iframe src=' + data.url + ' style="display:none;"></iframe>');
                        },
                        error: function (data, textStatus, xhr) {
                            plugin = data.plugin;
                            $('body').append('<iframe src=' + data.url + ' style="display:none;"></iframe>');
                        }
                    });
                    break;
                case "generate":

                    break;
                case "deploy":
                    break;
                default:

            }
        },
        onTabClick: function (tab, navigation, index) { }
    });
});

$(document).ready(function () {
    $('[data-type="toggle-switch"]').bootstrapSwitch({
        onText: "Yes",
        offText: "No",
        state: true
    });
    $('[data-type="toggle-switch-master"]').bootstrapSwitch({
        onText: "Y",
        offText: "N",
        state: true
    });
    var pages = new Array();

    $('[data-type="toggle-switch"]').on('switchChange.bootstrapSwitch', function (event, state) {
        debugger;
        $('[data-pagecount]').text($('[data-type="toggle-switch"]:checked').length);
        if (state.value) { pages.push($(this).data('filename')); }
        else { pages.pop($(this).data('filename')) };
    });
    $('[data-action]').on('click', function () {
        switch ($(this).data('action')) {
            case "ProcessPages":
                debugger;

                //                $('[data-type="toggle-switch"]:checked').each(function () {
                //                    pages.push($(this).data('filename'));
                //                });
                $.cookie('ProcessPages', pages, { path: '/' });
                amplify.request("ProcessPages", {
                    method: "ProcessPages"
                }, function (data) {
                    //data
                });
                break;
            case "CreateCompany":
                company.Name = $('div[data-control="CreateCompany"]').find('[data-name="Name"]').val();
                company.Domain = company.Name.toLowerCase();
                company.DefaultVersion = $('div[data-control="CreateCompany"]').find('[data-name="DefaultVersion"]').val();
                company.StartUp = $('div[data-control="CreateCompany"]').find('[data-name="StartUp"]').val();
                company._id = $('div[data-control="CreateCompany"]').find('[data-name="_id"]').val();
                company.CID = parseFloat($('div[data-control="CreateCompany"]').find('[data-name="CID"]').val()) + 1;
                company.CreatedDate = null;
                company.ModifiedDate = null;
                company.AssetLocation = '/' + company.Name + '/';
                company.Versions = null;
                debugger;
                $.ajax({
                    type: 'POST',
                    url: "/admin/Company/Create",
                    cache: false,
                    data: JSON.stringify({ company: company }),
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data, textStatus, xhr) {
                    },
                    error: function (data, textStatus, xhr) {
                    }
                });
            case "CreateVersion":
                version.VersionName = $('div[data-control="CreateVersion"]').find('[data-name="VersionName"]').val();
                version.VersionHTML = $('div[data-control="CreateVersion"]').find('[data-name="VersionHTML"]').val();
                version.IsDefault = $('div[data-control="CreateCompany"]').find('[data-type="toggle-switch-master"]:checked').length > 0;
                version._id = $('div[data-control="CreateVersion"]').find('[data-name="_id"]').val();
                version.VersionID = parseFloat($('div[data-control="CreateVersion"]').find('[data-name="VersionID"]').val()) + 1;
                version.CreatedDate = null;
                version.ModifiedDate = null;
                version.Pages = null;
                version.GlobalPlugins = null;
                $.ajax({
                    type: 'POST',
                    url: "/admin/Version/Create",
                    cache: false,
                    data: JSON.stringify({ version: version }),
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data, textStatus, xhr) {
                    },
                    error: function (data, textStatus, xhr) {
                    }
                });
            default:

        }
    });
});
$(document).ready(function () {
    var options = {};
    $('.drilldown').drilldown(options);
});
$(document).ready(function () {
    $('#pagelist').dataTable({
        "paging": true,
        "ordering": false,
        "info": false,
        "bLengthChange": false,
        "oLanguage": {
            "oPaginate": {
                "sFirst": "|<", // This is the link to the first page
                "sPrevious": "<", // This is the link to the previous page
                "sNext": ">", // This is the link to the next page
                "sLast": ">|" // This is the link to the last page
            }
        }
    });
});

$(document).ready(function () {
    amplify.request.define("ProcessPages", "ajax", {
        url: "/admin/version/{method}",
        type: "GET"
    });
    amplify.request.define("CreateCompany", "ajax", {
        url: "/admin/Company/CreateCompany",
        type: "POST"
    });
});

